/*
 * Copyright (C) 2014 VenomVendor <info@VenomVendor.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.bocai.dahuatech.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bocai.dahuatech.Bean.AddressListBean;
import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.IndividualBean;
import com.bocai.dahuatech.Bean.PointShopBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.ui.activity.LoginActivity;
import com.bocai.dahuatech.ui.activity.RegistDistributorSecendActivity;
import com.bocai.dahuatech.ui.pressent.AddressIdCallBack;
import com.bocai.dahuatech.ui.pressent.PointListPressent;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.DialogUtil;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.List;

import rx.Observer;

public class PointsAdapterHolder extends RecyclerView.Adapter<PointsAdapterHolder.ViewHolder> implements AddressIdCallBack {


    OnItemClickListener mItemClickListener;
    private Context context;
    PopupWindow mHeadPopWindow;
    FlowAdapter adapter;
    List<PointShopBean.ContentEntity> datas;
    public String start="{\"content\":";
    public String end="}";
    AddressListBean bean;
    //popwindow控件
    private ImageView ivDismissPop;
    private ListView lv_pop_point_exchange;
    TextView tvPopModel,tvPopName,tvPopPoint,tvPopDown,tvPopAdd,tvPopNum,tvPopTotalPoint,tvCommit;
    ImageView ivPopPic;
    PointListPressent pressent;
    int addrId;
    Double userPoint;//可用华积分
    public PointsAdapterHolder(Context context,List<PointShopBean.ContentEntity> datas,Double userPoint,PointListPressent pressent) {
        this.context = context;
        this.datas=datas;
        this.pressent=pressent;
        this.userPoint=userPoint;
    }
    public void addDatas(List<PointShopBean.ContentEntity> list){
        datas.addAll(list);
        this.notifyDataSetChanged();
    }
    public Observer<BaseBean> addrsObserver=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            Toast.makeText(context, R.string.neterror, Toast.LENGTH_SHORT).show();
            Log.e("error",e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean) {
            if(baseBean.getReturnNo().equals("1")){
                String result= AESUtils.decode(baseBean.getContent());
                result=start+result+end;
                Log.e("result",result);
                bean=new Gson().fromJson(result,AddressListBean.class);
                addrId=bean.getContent().get(0).getFID();
                setAddrAdapter();
            }
        }
    };

    private void setAddrAdapter() {
        lv_pop_point_exchange.setAdapter(new PointExchangeAddrAdapter(context,bean.getContent(),this));
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final LayoutInflater mInflater = LayoutInflater.from(parent.getContext());
        final View sView = mInflater.inflate(R.layout.points_item, parent, false);
        return new ViewHolder(sView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Glide.with(context).load(datas.get(position).getFImgSrc())
                .into(holder.ivPic);
        holder.tvModel.setText(datas.get(position).getFOutModel());
        holder.tvName.setText(datas.get(position).getFItemName());
        holder.tvPoint.setText(datas.get(position).getFPoint() + context.getResources().getString(R.string.huapoint));
        if(SharePrefencesUtil.getFAccessFlag(context)==2){

            holder.tvPrice.setText(context.getResources().getString(R.string.money) +datas.get(position).getFPrice());
        }else{
            holder.tvPrice.setText("");
        }
        holder.tv_point_exchange.setOnClickListener(new MyOnClickListner(position, holder.tv_point_exchange));
    }
    private void showPopwindow(View v,int position) {
            View view = LayoutInflater.from(context).inflate(R.layout.pop_point_exchange, null);
            ivDismissPop= (ImageView) view.findViewById(R.id.iv_dismiss_pop);
            tvPopModel= (TextView) view.findViewById(R.id.tv_pointdetail_model);
            tvPopName= (TextView) view.findViewById(R.id.tv_pointdetail_name);
            tvPopPoint=(TextView)view.findViewById(R.id.tv_pointdetail_point);
            lv_pop_point_exchange= (ListView) view.findViewById(R.id.lv_pop_point_exchange);
            tvCommit=(TextView)view.findViewById(R.id.tv_pop_point_commit);
            View header= LayoutInflater.from(context).inflate(R.layout.pop_point_exchange_header,null);
            tvPopAdd= (TextView) header.findViewById(R.id.tv_pointdetail_add);
            tvPopDown=(TextView)header.findViewById(R.id.tv_pointdetail_down);
            tvPopTotalPoint=(TextView)header.findViewById(R.id.tv_pointdetail_price);
            tvPopNum=(TextView)header.findViewById(R.id.tv_pointdetail_num);
            lv_pop_point_exchange.addHeaderView(header);
            ivPopPic=(ImageView)view.findViewById(R.id.iv_pointdetail_pic);
            setdatas(position);
            pressent.getAddrList();
            tvCommit.setOnClickListener(new ChooseNumOnClickListener(position, tvPopNum, tvPopTotalPoint));
            tvPopAdd.setOnClickListener(new ChooseNumOnClickListener(position, tvPopNum, tvPopTotalPoint));
            tvPopDown.setOnClickListener(new ChooseNumOnClickListener(position,tvPopNum,tvPopTotalPoint));
            ivDismissPop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mHeadPopWindow.dismiss();
                }
            });
            mHeadPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT, true);
            mHeadPopWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            mHeadPopWindow.setAnimationStyle(android.R.style.Animation_Dialog);
            mHeadPopWindow.showAtLocation(v, Gravity.TOP, 0, 0);


    }

    @Override
    public void getAddrId(int addrId) {
        this.addrId=addrId;
    }

    class ChooseNumOnClickListener implements View.OnClickListener
    {
        private int position;
        private TextView tvTotalCount,tvTotalPoint;
        int totalCount=1;
        public ChooseNumOnClickListener(int position,View tvTotalCount,View tvTotalPoint)
        {
            this.position=position;
            this.tvTotalCount= (TextView) tvTotalCount;
            this.tvTotalPoint= (TextView) tvTotalPoint;

        }
        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {

                case R.id.tv_pointdetail_down:
                    totalCount=Integer.parseInt((tvTotalCount).getText().toString());


                        if(totalCount>1)
                        {
                            totalCount--;
                            if(datas.get(position).getFPoint() * totalCount>userPoint){
                                Toast.makeText(context,R.string.huapointinadequate,Toast.LENGTH_SHORT).show();
                            }else{
                            tvTotalCount.setText(totalCount+"");
                            tvTotalPoint.setText(context.getResources().getString(R.string.total) + (datas.get(position).getFPoint() * totalCount)+context.getResources().getString(R.string.huapoint));
                        }
                    }
                    break;
                case R.id.tv_pointdetail_add:
                    totalCount=Integer.parseInt(tvTotalCount.getText().toString());

                        totalCount++;
                    if(datas.get(position).getFPoint() * totalCount>userPoint){
                        Toast.makeText(context, R.string.huapointinadequate,Toast.LENGTH_SHORT).show();
                    }else {
                        tvTotalCount.setText(totalCount + "");
                        tvTotalPoint.setText(context.getResources().getString(R.string.total) + (datas.get(position).getFPoint() * totalCount) + context.getResources().getString(R.string.huapoint));
                    }
                    break;
                case R.id.tv_pop_point_commit:
                    totalCount=Integer.parseInt(tvTotalCount.getText().toString());
                    pressent.commitPoint(datas.get(position).getFID(),datas.get(position).getFPoint()*totalCount,totalCount,addrId);
                    break;
            }
        }
    }

    /**
     * 提交兑换返回
     */
    public Observer<BaseBean> commitObserver =new Observer<BaseBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            Toast.makeText(context, R.string.neterror, Toast.LENGTH_SHORT).show();
            Log.e("error",e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean) {
            Log.e("result",baseBean.getReturnInfo());
            Toast.makeText(context,baseBean.getReturnInfo(),Toast.LENGTH_SHORT).show();
        }
    };
    class MyOnClickListner implements View.OnClickListener{
        int position;
        View v;
        public  MyOnClickListner(int position,View v){
            this.position=position;
            this.v=v;
        }
        @Override
        public void onClick(View v) {
            if (SharePrefencesUtil.getFAccessFlag(context) == 0)//游客 去登录
            {
                {
                    DialogUtil.dialogForTwoButton(context, R.string.nologin, R.string.know, R.string.tologin, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(context, LoginActivity.class);
                            intent.putExtra("tologin", false);
                            context.startActivity(intent);
                            DialogUtil.dismissTowDialog();
                        }
                    });
                }
            } else if (SharePrefencesUtil.getFAccessFlag(context) != 2) //个人  去认证
            {

                DialogUtil.dialogForTwoButton(context, R.string.notexchangepoint, R.string.know, R.string.toauthentication, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (SharePrefencesUtil.getFAccessFlag(context) == 6) {
                            DialogUtil.dismissTowDialog();
                            DialogUtil.dialogForOneButton(context, R.string.alreadysubmitdata, R.string.know);
                        } else if (SharePrefencesUtil.getFAccessFlag(context) == 7) {
                            Intent intent1 = new Intent(context, RegistDistributorSecendActivity.class);
                            IndividualBean bean = new IndividualBean();
                            intent1.putExtra("register", bean);
                            intent1.putExtra("what", "certifiled");
                            context.startActivity(intent1);
                            DialogUtil.dismissTowDialog();
//                            pressent.finishActivity();
                        }
                    }
                });
            } else {
                showPopwindow(v,position);
            }
        }
    }
    private void setdatas(int position) {
        Glide.with(context).load(datas.get(position).getFImgSrc())
                .error(R.mipmap.product_photo_defalt)
                .into(ivPopPic);
        tvPopModel.setText(datas.get(position).getFOutModel());
        tvPopName.setText(datas.get(position).getFItemName());
        tvPopPoint.setText(datas.get(position).getFPoint() +context.getResources().getString(R.string.huapoint));
        tvPopTotalPoint.setText(datas.get(position).getFPoint() + context.getResources().getString(R.string.huapoint));
        tvPopNum.setText("1");
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
        this.mItemClickListener = mItemClickListener;
    }


    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        TextView tv_point_exchange,tvModel,tvName,tvPrice,tvPoint;
        ImageView ivPic;

        public ViewHolder(View view) {
            super(view);
            tv_point_exchange= (TextView) view.findViewById(R.id.tv_point_exchange);
            tvModel= (TextView) view.findViewById(R.id.tv_pointsshop_model);
            tvName= (TextView) view.findViewById(R.id.tv_pointsshop_name);
            tvPoint= (TextView) view.findViewById(R.id.tv_pointsshop_point);
            tvPrice= (TextView) view.findViewById(R.id.tv_pointsshop_price);
            ivPic= (ImageView) view.findViewById(R.id.iv_pointsshop_pic);
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (mItemClickListener != null) {
//                mItemClickListener.onItemClick(v, getPosition());
                mItemClickListener.onItemClick(v, getLayoutPosition());
            }
        }

    }

}
